package Drivers;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import DBPack.DBStatement;
import DBPack.Rail;
import DBPack.RailStation;

public class RailDriver {
	public static Rail[] getAllRailList() {
		try{
			String query="SELECT * FROM rail " ;
			PreparedStatement ps=(PreparedStatement) DBStatement.getMainConnection().prepareStatement(query);
			ResultSet result = ps.executeQuery();
			if(result.next())
				return convertRailToArray(result);
		}  catch(SQLException e) {
		} catch (Exception e) {
		}
		return null;
	}
	
	public static Rail[] getRailList(String input) {
			try{
				String query="SELECT * FROM rail where code like ? or name like ? order by name asc,code asc";
				PreparedStatement ps=(PreparedStatement) DBStatement.getMainConnection().prepareStatement(query);
				ps.setString(1, input+"%");
				ps.setString(2, input+"%");
				ResultSet result = ps.executeQuery();
				if(result.next())
					return convertRailToArray(result);
			}  catch(SQLException e) {
			} catch (Exception e) {
			}
			return null;			
	}
	public static RailStation[] getRailStationList(String railCode) {
		try{
			String query="SELECT * FROM rail_stations where rail_code=?" ;
			PreparedStatement ps=(PreparedStatement) DBStatement.getMainConnection().prepareStatement(query);
			ps.setString(1, railCode);
			ResultSet set = ps.executeQuery();
			if(set.next())
				return convertRailStationToArray(set);
		}  catch(SQLException e) {
			e.printStackTrace();
			return new RailStation[0];
		} catch (Exception e) {
			e.printStackTrace();
			return new RailStation[0];
		}
		return new RailStation[0];
		
	}
	private static Rail[] convertRailToArray(ResultSet result) throws SQLException{
		int N = 0;
		result.beforeFirst();
		while(result.next()) N++;
		result.beforeFirst();
		Rail[] list = new Rail[N];
		int i=0;
		while(result.next())
			list[i++] = new Rail(result.getInt("rail_id"), result.getString("name"),result.getString("code"),result.getString("departure"),result.getString("arrival"),result.getString("type"));
		return list;

	}
	private static RailStation[] convertRailStationToArray(ResultSet result) throws SQLException{
		int N = 0;
		result.beforeFirst();
		while(result.next()) N++;
		result.beforeFirst();
		RailStation[] list = new RailStation[N];
		int i=0;
		while(result.next())
			list[i++] = new RailStation(result.getInt("rail_station_id"), result.getString("rail_code"),result.getString("station_name"),result.getString("station_order"));
		return list;

	}
	

}
